package com.kfm.jdbc.day04;

import java.sql.*;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

public class MyDataSource extends MyAbstractDataSouce{
    // 1. 定义数据库连接信息
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    // 2. 定义连接池信息
    private int initSize = 5;
    private int maxSize = 10;
    private int currSize;

    // 3. 定义连接池数组
    private LinkedList<Connection> pool;

    public MyDataSource() {
    }

    public MyDataSource(String driverClassName, String url, String username, String password) {
        this.driverClassName = driverClassName;
        this.url = url;
        this.username = username;
        this.password = password;
    }

    /**
     * 初始化连接池
     *  1. 加载驱动
     *  2. 初始化连接池中的链接
     *
     */
    private void init() {
        System.out.println("初始化连接池");
        // 0. 初始化连接池数组
        pool = new LinkedList<>();
        // 1. 加载驱动
        try {
            Class.forName(driverClassName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("加载驱动失败，driverClassName=" + driverClassName + "。", e);
        } catch (NullPointerException e){
            throw new RuntimeException("加载驱动失败，driverClassName 不能为 null", e);
        }
        // 2. 初始化连接池
        for (int i = 0; i < initSize; i++) {
            Connection connection = null;
            try {
                // 3. 创建连接
                connection = getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            // 4. 将连接添加到连接池中
            pool.add(connection);
        }
    }

    /**
     * 释放连接 【不推荐】
     *  弊端： 不能控制用户行为，用户可能会将连接关闭，导致连接池中的连接不够用
     * @param connection
     */
    public void close(Connection connection){
        // 1. 判断连接池是否已满
        if (pool.size() >= maxSize) {
            // 2. 已满，关闭连接
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭连接失败", e);
            }
        } else {
            // 3. 未满，将连接添加到连接池中
            pool.add(connection);
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (pool == null) {
            // 初始化连接池
            init();
        }
        // 1. 判断连接池是否还有连接
        if (pool.size() > 0) {
            // 2. 从连接池中获取连接
            Connection connection = pool.removeFirst();
            // 3. 返回连接
            return connection;
        }
        // 4. 没有连接。判断当前连接池大小是否小于最大连接池大小
        if (currSize >= maxSize) {
            // 5. 抛出异常
            throw new RuntimeException("连接池已满, 请稍后再试");
        } else {
            // 6. 创建连接
            Connection connection = null;
            try {
                connection = new MyConnection(DriverManager.getConnection(url, username, password));
            } catch (SQLException e) {
                throw new RuntimeException("获取连接失败，url=" + url + ", username=" + username + ", password=" + password + "。", e);
            }
            // 7. 更新当前连接池大小
            currSize ++;
            // 8. 返回连接
            return connection;
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }


    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getInitSize() {
        return initSize;
    }

    public void setInitSize(int initSize) {
        this.initSize = initSize;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    /**
     * 自定义连接对象
     * 静态代理： 代理类和被代理类实现同一个接口，代理类中持有被代理类的引用
     */
    class MyConnection implements Connection {

        // 被代理的连接
        private Connection connection;

        public MyConnection(Connection connection){
            this.connection = connection;
        }

        @Override
        public Statement createStatement() throws SQLException {
            return connection.createStatement();
        }

        @Override
        public PreparedStatement prepareStatement(String sql) throws SQLException {
            return connection.prepareStatement(sql);
        }

        @Override
        public CallableStatement prepareCall(String sql) throws SQLException {
            return connection.prepareCall(sql);
        }

        @Override
        public String nativeSQL(String sql) throws SQLException {
            return connection.nativeSQL(sql);
        }

        @Override
        public void setAutoCommit(boolean autoCommit) throws SQLException {

        }

        @Override
        public boolean getAutoCommit() throws SQLException {
            return false;
        }

        @Override
        public void commit() throws SQLException {
            connection.commit();
        }

        @Override
        public void rollback() throws SQLException {

        }

        @Override
        public void close() throws SQLException {
            // 1. 判断连接池是否已满
            if (pool.size() >= maxSize) {
                // 2. 已满，关闭连接
                connection.close();
            } else {
                // 3. 未满，将连接添加到连接池中
                pool.add(this);
            }
        }

        @Override
        public boolean isClosed() throws SQLException {
            return false;
        }

        @Override
        public DatabaseMetaData getMetaData() throws SQLException {
            return null;
        }

        @Override
        public void setReadOnly(boolean readOnly) throws SQLException {

        }

        @Override
        public boolean isReadOnly() throws SQLException {
            return false;
        }

        @Override
        public void setCatalog(String catalog) throws SQLException {

        }

        @Override
        public String getCatalog() throws SQLException {
            return null;
        }

        @Override
        public void setTransactionIsolation(int level) throws SQLException {

        }

        @Override
        public int getTransactionIsolation() throws SQLException {
            return 0;
        }

        @Override
        public SQLWarning getWarnings() throws SQLException {
            return null;
        }

        @Override
        public void clearWarnings() throws SQLException {

        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
            return null;
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return null;
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
            return null;
        }

        @Override
        public Map<String, Class<?>> getTypeMap() throws SQLException {
            return null;
        }

        @Override
        public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

        }

        @Override
        public void setHoldability(int holdability) throws SQLException {

        }

        @Override
        public int getHoldability() throws SQLException {
            return 0;
        }

        @Override
        public Savepoint setSavepoint() throws SQLException {
            return null;
        }

        @Override
        public Savepoint setSavepoint(String name) throws SQLException {
            return null;
        }

        @Override
        public void rollback(Savepoint savepoint) throws SQLException {

        }

        @Override
        public void releaseSavepoint(Savepoint savepoint) throws SQLException {

        }

        @Override
        public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return null;
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return null;
        }

        @Override
        public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
            return null;
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
            return null;
        }

        @Override
        public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
            return null;
        }

        @Override
        public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
            return null;
        }

        @Override
        public Clob createClob() throws SQLException {
            return null;
        }

        @Override
        public Blob createBlob() throws SQLException {
            return null;
        }

        @Override
        public NClob createNClob() throws SQLException {
            return null;
        }

        @Override
        public SQLXML createSQLXML() throws SQLException {
            return null;
        }

        @Override
        public boolean isValid(int timeout) throws SQLException {
            return false;
        }

        @Override
        public void setClientInfo(String name, String value) throws SQLClientInfoException {

        }

        @Override
        public void setClientInfo(Properties properties) throws SQLClientInfoException {

        }

        @Override
        public String getClientInfo(String name) throws SQLException {
            return null;
        }

        @Override
        public Properties getClientInfo() throws SQLException {
            return null;
        }

        @Override
        public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
            return null;
        }

        @Override
        public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
            return null;
        }

        @Override
        public void setSchema(String schema) throws SQLException {

        }

        @Override
        public String getSchema() throws SQLException {
            return null;
        }

        @Override
        public void abort(Executor executor) throws SQLException {

        }

        @Override
        public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

        }

        @Override
        public int getNetworkTimeout() throws SQLException {
            return 0;
        }

        @Override
        public <T> T unwrap(Class<T> iface) throws SQLException {
            return null;
        }

        @Override
        public boolean isWrapperFor(Class<?> iface) throws SQLException {
            return false;
        }
    }
}
